package com.sanpu.kxe.business.repay.view;

import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseTitleActivity;
import com.sanpu.kxe.business.card.bean.BankInfoOutput;
import com.sanpu.kxe.business.card.view.AddBankSetupActivity;
import com.sanpu.kxe.business.repay.contract.RefundContract;
import com.sanpu.kxe.business.repay.contract.RepayConfig;
import com.sanpu.kxe.business.repay.model.RepayModel;
import com.sanpu.kxe.business.repay.presenter.RefundPresenter;
import com.sanpu.kxe.business.trade.adapter.ChooseBankAdapter;
import com.sanpu.kxe.common.utils.CommonUtils;
import com.sanpu.kxe.common.utils.SingleCheckListener;
import com.sanpu.kxe.module.dialog.GlobalDialog;
import com.sanpu.kxe.module.dialog.HintDialog;
import com.sanpu.kxe.module.widget.EditTextWithDel;
import com.sanpu.kxe.utils.IntentTool;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Description：代还-还款
 * Created by 薛勇军 on 2019/4/10.
 */

public class RefundActivity extends BaseTitleActivity implements RefundContract.View {

    @Bind(R.id.containLayout)
    ScrollView containLayout;
    @Bind(R.id.repayMoneyGet)
    EditTextWithDel repayMoneyGet;
    @Bind(R.id.cardBalanceGet)
    EditTextWithDel cardBalanceGet;
    @Bind(R.id.refundHintTv)
    TextView refundHintTv;

    @Bind(R.id.payCardTv)
    TextView payCardTv;
    @Bind(R.id.accountCardTv)
    TextView accountCardTv;
    @Bind(R.id.refundDayTv)
    TextView refundDayTv;
    @Bind(R.id.accountArrowIv)
    ImageView accountArrowIv;

    private ChooseBankAdapter mBankAdapter;

    private SingleCheckListener singleCheckListener;

    private RefundContract.Presenter mPresenter;

    private List<String> selectList = new ArrayList<>();

    private ArrayList<BankInfoOutput> mOutBankList = new ArrayList<>();

    private float minFloat, maxFloat, minBalance, percent;

    private String apprtId, cardId, settleCardId, cardNo, dueDay;

    private boolean isOptionalMcc;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_refund;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setTitle("还款计划");
        mBankAdapter = new ChooseBankAdapter(mContext, new ArrayList<BankInfoOutput>());
    }

    @Override
    protected void initData() {
        super.initData();
        BankInfoOutput infoOutput = (BankInfoOutput) getIntent().getSerializableExtra(RepayConfig.INTENT_BANKINFO);
        isOptionalMcc = getIntent().getBooleanExtra(RepayConfig.INTENT_ISOPTIONALMCC, false);
        cardId = getIntent().getStringExtra(RepayConfig.INTENT_BINDCARDID);
        apprtId = getIntent().getStringExtra(RepayConfig.INTENT_APPRTID);
        String maxAmount = getIntent().getStringExtra(RepayConfig.INTENT_MAXAMOUNT);
        String minAmount = getIntent().getStringExtra(RepayConfig.INTENT_MINAMOUNT);
        minFloat = TextUtils.isEmpty(minAmount) ? 500 : Float.parseFloat(minAmount);
        maxFloat = TextUtils.isEmpty(maxAmount) ? 100000 : Float.parseFloat(maxAmount);
        repayMoneyGet.setHint("不低于" + minFloat + " 不高于" + maxFloat);
        String creditMinBalance = getIntent().getStringExtra(RepayConfig.INTENT_CREDITMINBALANCE);
        String balancePercent = getIntent().getStringExtra(RepayConfig.INTENT_BALANCEPERCENT);
        minBalance = TextUtils.isEmpty(creditMinBalance) ? 500 : Float.parseFloat(creditMinBalance);
        percent = TextUtils.isEmpty(balancePercent) ? 5 : Float.parseFloat(balancePercent);
        cardBalanceGet.setHint("不低于" + minBalance);

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("温馨提示：");
        stringBuffer.append("\r\n");
        stringBuffer.append("1.一张信用卡只能制定一本计划，计划本中的计划未执行完，不能制定新计划本");
        stringBuffer.append("\r\n");
        stringBuffer.append("2.制定计划流程：①填写信息②点击制定③查看计划④执行计划");
        stringBuffer.append("\r\n");
        stringBuffer.append("3.单笔消费金额和还款的次数由计划还款金额和信用卡内余额决定，计划还款金额越少，卡内余额越多，还款次数越少");
        stringBuffer.append("\r\n");
        stringBuffer.append("4.卡内余额不低于");
        stringBuffer.append(minFloat);
        stringBuffer.append("元且不能低于");
        stringBuffer.append(percent);
        stringBuffer.append("%计划还款金额");
        stringBuffer.append("\r\n");
        refundHintTv.setText(stringBuffer);

        if (infoOutput != null) {
            cardNo = infoOutput.getBankNo();
            dueDay = infoOutput.getDueDay();
            String bankNo = infoOutput.getBankNo();
            String cardText = infoOutput.getBankName() + "（" + bankNo.substring(bankNo.length() - 4) + "）";
            payCardTv.setText(cardText);
            accountCardTv.setText(cardText);
            accountCardTv.setTag(bankNo);
            refundDayTv.setText("每月" + infoOutput.getDueDay() + "号");
            accountArrowIv.setVisibility(View.GONE);
            refundDayTv.setEnabled(false);
        }
        selectList = RepayModel.getInstance().getSelectList();
        mPresenter = new RefundPresenter(this);
        mPresenter.selectUrmBankPage();
    }

    @OnClick({R.id.next, R.id.refundDayTv, R.id.accountCardTv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.next:
                String repayMoney = repayMoneyGet.getText().toString();
                String cardBalance = cardBalanceGet.getText().toString();
                String refundDay = refundDayTv.getText().toString();
                String remarkHint = checkInput();
                if (!TextUtils.isEmpty(remarkHint)) {
                    GlobalDialog dialog = new GlobalDialog(mContext)
                            .title("温馨提示")
                            .content(remarkHint);
                    dialog.show();
                    return;
                }
                mPresenter.makePlan(cardId, apprtId, repayMoney, cardBalance, settleCardId, refundDay, isOptionalMcc);
                break;
            case R.id.refundDayTv:
                if (singleCheckListener == null) {
                    singleCheckListener = new SingleCheckListener(RefundActivity.this);
                }
                singleCheckListener.handleCheck(containLayout, refundDayTv, selectList);
                break;
            case R.id.accountCardTv:
//                bankDialog();
                break;
        }
    }

    /**
     * 提现银行卡对话框
     */
    private void bankDialog() {
        String bankNo = accountCardTv.getTag() != null ? String.valueOf(accountCardTv.getTag()) : null;
        int checkIndex = -1;
        if (!TextUtils.isEmpty(bankNo)) {
            for (int i = 0; i < mOutBankList.size(); i++) {
                if (TextUtils.equals(bankNo, mOutBankList.get(i).getBankNo())) {
                    checkIndex = i;
                }
            }
        }
        mBankAdapter.setCheckPosition(checkIndex);
        mBankAdapter.setNotifyData(mOutBankList);
        final View header = LayoutInflater.from(mContext).inflate(R.layout.layout_choose_bank_header, null);
        final DialogPlus dialog = DialogPlus.newDialog(this)
                .setAdapter(mBankAdapter)
                .setHeader(header)
                .setFooter(R.layout.layout_choose_credit_bank_foot)
                .setGravity(Gravity.BOTTOM)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                        if (position < 0) return;
                        dialog.dismiss();
                        if (mOutBankList.size() == position) {
                            HintDialog hintDialog = new HintDialog(mContext)
                                    .title("添加信用卡号说明")
                                    .content(CommonUtils.generateHintView(mContext, 0,
                                            "添加新的信用卡后需重新进入当前页进行绑定信用卡"));
                            hintDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    IntentTool.startActivity(mContext, AddBankSetupActivity.class);
                                }
                            });
                            hintDialog.show();
                            return;
                        }
                        String bankNo = mOutBankList.get(position).getBankNo();
                        String cardText = mOutBankList.get(position).getBankName() + "（" + bankNo.substring(bankNo.length() - 4) + "）";
                        accountCardTv.setText(cardText);
                        accountCardTv.setTag(bankNo);
                        if (TextUtils.equals(bankNo, cardNo)) {
                            refundDayTv.setText("每月" + dueDay + "号");
                            accountArrowIv.setVisibility(View.GONE);
                            refundDayTv.setEnabled(false);
                            settleCardId = null;
                        } else {
                            accountArrowIv.setVisibility(View.VISIBLE);
                            refundDayTv.setEnabled(true);
                            settleCardId = mOutBankList.get(position).getBankId();
                        }
                    }
                })
                .setExpanded(false)
                .create();
        dialog.show();

        header.findViewById(R.id.arrow).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }


    @Override
    public void setOutBankData(List<BankInfoOutput> bankInfoOutputs) {
        mOutBankList.clear();
        if (bankInfoOutputs != null) {
            mOutBankList.addAll(bankInfoOutputs);
        }
    }

    @Override
    protected void setListener() {
        super.setListener();
        repayMoneyGet.addTextChangedListener(new TextWatcher() {
            private String beforeEdit;
            private boolean resetText = false;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (!resetText) {
                    Selection.getSelectionEnd(s);
                    beforeEdit = s.toString();
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!resetText) {
                    resetText = true;
                    CharSequence input = s.subSequence(start, start + count);
                    if (TextUtils.isEmpty(beforeEdit)) {
                        //初始为空不让输小数点
                        if (TextUtils.equals(".", input)) {
                            resetText(repayMoneyGet, "0.");
                        }
                    }
                    if (TextUtils.equals("0", beforeEdit)) {
                        //初始为0不让输数字
                        if (!TextUtils.isEmpty(input) && CommonUtils.isNumeric(input.toString())) {
                            resetText(repayMoneyGet, input.toString());
                        }
                    }
                    String text = s.toString();
                    if (text.contains(".")) {
                        //初始包含小数点，小数点后限两位数字
                        String decimals = text.substring(text.lastIndexOf(".") + 1, text.length());
                        if (decimals.length() > 2) {
                            resetText(repayMoneyGet, beforeEdit);
                        }
                    }
                    resetText = false;
                } else {
                    resetText = false;
                }
            }

            @Override
            public void afterTextChanged(Editable edt) {
            }
        });
        cardBalanceGet.addTextChangedListener(new TextWatcher() {
            private String beforeEdit;
            private boolean resetText = false;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (!resetText) {
                    Selection.getSelectionEnd(s);
                    beforeEdit = s.toString();
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!resetText) {
                    resetText = true;
                    CharSequence input = s.subSequence(start, start + count);
                    if (TextUtils.isEmpty(beforeEdit)) {
                        //初始为空不让输小数点
                        if (TextUtils.equals(".", input)) {
                            resetText(cardBalanceGet, "0.");
                        }
                    }
                    if (TextUtils.equals("0", beforeEdit)) {
                        //初始为0不让输数字
                        if (!TextUtils.isEmpty(input) && CommonUtils.isNumeric(input.toString())) {
                            resetText(cardBalanceGet, input.toString());
                        }
                    }
                    String text = s.toString();
                    if (text.contains(".")) {
                        //初始包含小数点，小数点后限两位数字
                        String decimals = text.substring(text.lastIndexOf(".") + 1, text.length());
                        if (decimals.length() > 2) {
                            resetText(cardBalanceGet, beforeEdit);
                        }
                    }
                    resetText = false;
                } else {
                    resetText = false;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    /**
     * 重置
     */
    public void resetText(EditText editText, String reset) {
        if (reset == null) reset = "";
        editText.setText(reset);
        CharSequence text = editText.getText();
        if (text != null) {
            Spannable spanText = (Spannable) text;
            Selection.setSelection(spanText, text.length());
        }
    }

    /**
     * 验证输入的值
     *
     * @return 为空表示验证通过
     */
    private String checkInput() {
        String repayMoney = repayMoneyGet.getText().toString();
        if (TextUtils.isEmpty(repayMoney)) {
            return "请输入计划还款金额";
        }
        float repayFloat = Float.parseFloat(repayMoney);
        if (repayFloat < minFloat || repayFloat > maxFloat) {
            return "计划还款金额" + repayMoneyGet.getHint();
        }
        String cardBalance = cardBalanceGet.getText().toString();
        if (TextUtils.isEmpty(cardBalance)) {
            return "请输入信用卡内余额";
        }
        float balance = Float.parseFloat(cardBalance);
        if (balance < minBalance || balance < repayFloat * percent / 100) {
            return "信用卡内余额不能低于" + minBalance + "且不低于" + percent + "%的计划还款金额";
        }
        return "";
    }

    @Override
    protected boolean hasBindEventBus() {
        return false;
    }

    @Override
    public void setPresenter(RefundContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
